#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
微信支付回调接口
"""

from flask import Blueprint, request, current_app
from flasgger import swag_from
from app.utils.response import success_response, error_response
from app.utils.wechat_pay_enhanced import WeChatPayEnhanced

# 创建蓝图
wechat_pay_bp = Blueprint('wechat_pay', __name__)


@wechat_pay_bp.route('/payments/wechat/notify', methods=['POST'])
@swag_from({
    "tags": ["微信支付"],
    "summary": "微信支付回调通知",
    "description": "微信支付回调通知接口，处理支付结果\n\n**⚠️ 此接口由微信服务器调用，无需认证**",
    "parameters": [
        {
            "name": "body",
            "in": "body",
            "description": "微信支付回调XML数据",
            "required": True,
            "schema": {
                "type": "string",
                "example": "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>"
            }
        }
    ],
    "responses": {
        "200": {
            "description": "处理成功",
            "schema": {
                "type": "string",
                "example": "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>"
            }
        },
        "400": {
            "description": "处理失败",
            "schema": {
                "type": "string",
                "example": "<xml><return_code><![CDATA[FAIL]]></return_code></xml>"
            }
        }
    }
})
def wechat_pay_notify():
    """微信支付回调通知"""
    try:
        # 获取原始XML数据
        xml_data = request.get_data(as_text=True)
        
        if not xml_data:
            current_app.logger.error("微信支付回调：未接收到数据")
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[未接收到数据]]></return_msg></xml>", 400
        
        current_app.logger.info(f"接收到微信支付回调通知: {xml_data[:200]}...")
        
        # 初始化微信支付服务
        try:
            wechat_pay = WeChatPayEnhanced()
        except ValueError as e:
            current_app.logger.error(f"微信支付配置错误: {str(e)}")
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[配置错误]]></return_msg></xml>", 500
        
        # 处理回调通知
        response_xml = wechat_pay.handle_notify(xml_data)
        
        # 根据处理结果返回相应状态码
        if 'SUCCESS' in response_xml:
            current_app.logger.info("微信支付回调处理成功")
            return response_xml, 200
        else:
            current_app.logger.warning("微信支付回调处理失败")
            return response_xml, 400
            
    except Exception as e:
        current_app.logger.error(f"微信支付回调异常: {str(e)}")
        return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[服务器错误]]></return_msg></xml>", 500


@wechat_pay_bp.route('/payments/query/<payment_no>', methods=['GET'])
@swag_from({
    "tags": ["微信支付"],
    "summary": "查询支付状态",
    "description": "主动查询微信支付状态\n\n**🔐 需要管理员权限**",
    "parameters": [
        {"name": "payment_no", "in": "path", "type": "string", "required": True, "description": "支付单号"}
    ],
    "responses": {
        "200": {
            "description": "查询成功",
            "schema": {
                "type": "object",
                "properties": {
                    "code": {"type": "integer", "example": 200},
                    "message": {"type": "string", "example": "查询成功"},
                    "data": {
                        "type": "object",
                        "properties": {
                            "payment_no": {"type": "string", "description": "支付单号"},
                            "status": {"type": "string", "description": "支付状态"},
                            "amount": {"type": "number", "description": "支付金额"},
                            "paid_at": {"type": "string", "description": "支付时间"}
                        }
                    }
                }
            }
        },
        "404": {"description": "支付记录不存在"},
        "500": {"description": "查询失败"}
    }
})
def query_payment_status(payment_no):
    """查询支付状态"""
    try:
        from app.models.payment import Payment
        
        # 查找支付记录
        payment = Payment.query.filter_by(payment_no=payment_no).first()
        if not payment:
            return error_response('支付记录不存在', 404)
        
        # 初始化微信支付服务
        try:
            wechat_pay = WeChatPayEnhanced()
        except ValueError as e:
            return error_response(f'微信支付配置错误: {str(e)}', 500)
        
        # 查询微信支付状态
        wechat_result = wechat_pay.query_payment_status(payment_no)
        
        if wechat_result:
            # 根据微信返回结果更新本地状态
            if wechat_result.get('trade_state') == 'SUCCESS':
                if payment.status != 1:
                    payment.status = 1
                    payment.transaction_id = wechat_result.get('transaction_id')
                    if not payment.paid_at:
                        from datetime import datetime
                        payment.paid_at = datetime.now()
                    
                    # 更新订单状态
                    if payment.order:
                        payment.order.status = 1
                        payment.order.updated_at = datetime.now()
                    
                        # 创建入场记录
                        from app.models.checkin_record import CheckinRecord
                        existing_record = CheckinRecord.query.filter_by(order_id=payment.order.id).first()
                        if not existing_record:
                            checkin_record = CheckinRecord.create_from_order(payment.order)
                            db.session.add(checkin_record)
                    
                    from app import db
                    db.session.commit()
        
        return success_response({
            'payment_no': payment.payment_no,
            'status': payment.get_status_text(),
            'amount': float(payment.amount),
            'paid_at': payment.paid_at.strftime('%Y-%m-%d %H:%M:%S') if payment.paid_at else None,
            'wechat_status': wechat_result.get('trade_state') if wechat_result else None
        }, '查询成功')
        
    except Exception as e:
        current_app.logger.error(f"查询支付状态异常: {str(e)}")
        return error_response('查询失败', 500) 